package gw.com.android.ui.me;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.ChatTokenRequest;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.Https;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.utils.CacheUtils;
import gw.com.android.utils.ThreadPool;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;

/**
 * 个人信息相关的所有请求
 *
 * @author jett
 * @since 2018-01-11.
 */
public class ProfileRequest {

    public void getUserInfo(final String phone, final HttpCallback<ProfileData> callBack) {
        acquireChatToken(new ChatTokenRequest.OnTokenListener() {
            @Override
            public void onSuccess(final String token) {
                ThreadPool.getInstance().execute(new Runnable() {
                    @Override
                    public void run() {
                        String isAnalyst = isUserAnalyst(token);//
                        if (!TextUtils.isEmpty(isAnalyst)) {//如果是分析师，则isUserAnalyst函数返回不是空
                            realGetAnalystInfo(phone, token, callBack);//那就按照分析师的查询方式
                        } else //如果不是分析师，那就按照普通用户的查询方式
                            realGetUserInfo(phone, token, callBack);
                    }
                });
            }

            @Override
            public void onFailure(Exception e) {
                if (callBack != null) {
                    callBack.onFailure(e);
                }
            }
        });
    }

    void modifyNickname(final String phone, final String nickname, final HttpCallback<String> callback) {
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                realModifyNickname(phone, nickname, callback);
            }
        });
    }

    void uploadAvatar(String path, final String num, final HttpCallback<String> callback) {
        File file = new File(path);
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/upload/uploadFile";
        new Https().url(url)
                .addParam("platform", "android")
                .addParam("fileDir", "pic/header/chat/front")
                .addParam("fileType", "showTrade")
                .addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.COMPANY_ID_TAG))
                .addUploadFile("file", "", file)
                .upload(new Https.UploadListener<String>() {
                    @Override
                    public void onUploading(long current, long total, boolean done) {
                        //Logger.i("uploadAvatar", "current = " + current + "  total " + total + "  percent = " + (current * 100F / total) + "%");
                    }

                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Exception exception = null;
                        try {
                            JSONObject json = new JSONObject(result);
                            JSONArray dataArr = json.optJSONArray("data");
                            if (dataArr != null && dataArr.length() > 0) {
                                JSONObject dataJson = dataArr.optJSONObject(0);
                                String domain = dataJson.optString("fileDomain");
                                String filePath = dataJson.optString("filePath");
                                modifyAvatar(num, domain + filePath, callback);
                                return;
                            }
                        } catch (JSONException e) {
                            exception = e;
                        }
                        if (callback != null) {
                            callback.onFailure(exception);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    private void modifyAvatar(final String num, final String avatar, final HttpCallback<String> callback) {
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                realModifyAvatar(num, avatar, callback);
            }
        });
    }

    void modifyGender(final String num, final String gender, final HttpCallback<String> callback) {
        acquireChatToken(new ChatTokenRequest.OnTokenListener() {
            @Override
            public void onSuccess(String token) {
                realModifyGender(num, token, gender, callback);
            }

            @Override
            public void onFailure(Exception e) {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

    private void acquireChatToken(ChatTokenRequest.OnTokenListener listener) {
        new ChatTokenRequest().acquire(listener);
    }

    /**
     * 查询普通客户
     *
     * @param phone
     * @param token
     * @param callback
     */
    private void realGetUserInfo(final String phone, String token, final HttpCallback<ProfileData> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getMemberInfo";
        new Https().url(url)
                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                //.addParam("userNos", "60051265")
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .addParam("mobilePhone", phone)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        //{"result":0,"errcode":"0","errmsg":"","data":null}
                        try {
                            JSONObject json = new JSONObject(result);
                            JSONObject dataJson = json.optJSONObject("data");
                            if (dataJson == null) {
                                createUser(phone, callback);
                            } else {
                                ProfileData profileData = parseUserInfo(dataJson);
                                if (callback != null) {
                                    callback.onSuccess(profileData);
                                }
                            }
                        } catch (JSONException e) {
                            if (callback != null) {
                                callback.onFailure(e);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    /**
     * @param token
     * @param callback
     */
    private void realGetAnalystInfo(final String phone, String token, final HttpCallback<ProfileData> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getUserInfoByAccountNo";
        new Https(url)
                .addParam("accountNo", GTConfig.instance().mCurName)
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        try {
                            JSONObject json = new JSONObject(result);
                            JSONObject dataJson = json.optJSONObject("data");
                            ProfileData profileData = parseUserInfo(dataJson);

                            if (TextUtils.isEmpty(profileData.mobilePhone))//如果后台没有返回这个手机号，那就用传进来的那个
                                profileData.mobilePhone = phone;
                            if (callback != null) {
                                callback.onSuccess(profileData);
                            }
                        } catch (JSONException e) {
                            if (callback != null) {
                                callback.onFailure(e);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    private ProfileData parseUserInfo(JSONObject dataJson) {
        if (dataJson == null) {
            return null;
        }
        ProfileData data = new ProfileData();
        data.userId = dataJson.optString("userId", null);
        data.mobilePhone = dataJson.optString("mobilePhone", null);
        data.avatar = dataJson.optString("avatar", null);
        if (dataJson.has("nickname"))
            data.nickname = dataJson.optString("nickname", null);
        else
            data.nickname = dataJson.optString("userName", null);

        data.clientGroup = dataJson.optString("clientGroup", null);
        data.groupType = dataJson.optString("groupType", null);
        data.email = dataJson.optString("email", null);
        data.gender = dataJson.optString("sex", null);
        return data;
    }

    public void realModifyNickname(String phone, final String nickname, final HttpCallback<String> callback) {
        String token = new ChatTokenRequest().acquire();
        if (TextUtils.isEmpty(token)) {
            postFailure(callback, null);
            return;
        }
        String isAnalyst = isUserAnalyst(token);
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/modifyNickname";
        Https https = new Https().url(url)
                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .addParam("nickname", nickname);
        if (!TextUtils.isEmpty(isAnalyst)) {//如果是分析师，那就
            https.addParam("type", "1"); // 修改类型，1：修改分析师头像，不传值为修改用户头像
            https.addParam("userId", isAnalyst);
        } else {
            https.addParam("mobilePhone", phone);
        }
        try {
            Response response = https.post();
            if (response != null && response.isSuccessful()) {
                Exception exception = null;
                JSONObject json = new JSONObject(response.body().string());
                JSONObject dataJson = json.optJSONObject("data");
                if (dataJson != null) {
                    boolean isOK = dataJson.optBoolean("isOK", false);
                    if (isOK) {
                        postSuccess(callback, nickname);
                        return;
                    } else {
                        String msg = dataJson.optString("msg");
                        if (!TextUtils.isEmpty(msg)) {
                            exception = new Exception(msg);
                        }
                        postFailure(callback, exception);
                        return;
                    }
                }
            }
        } catch (Exception e) {
            postFailure(callback, e);
            return;
        }
        postFailure(callback, null);
    }

    public void realModifyAvatar(final String num, final String avatar, final HttpCallback<String> callback) {
        String token = new ChatTokenRequest().acquire();
        if (TextUtils.isEmpty(token)) {
            postFailure(callback, null);
            return;
        }
        String isAnalyst = isUserAnalyst(token);
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/modifyAvatar";
        Https https = new Https().url(url)
                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .addParam("clientGroup", "notActive")
                //.addParam("userId", "")
                .addParam("ip", "127.0.0.100")
                .addParam("avatar", avatar);
        if (!TextUtils.isEmpty(isAnalyst)) {//如果是分析师，那就
            https.addParam("type", "1"); // 修改类型，1：修改分析师头像，不传值为修改用户头像
            https.addParam("userId", isAnalyst);
        } else {
            https.addParam("mobilePhone", num);
        }

        Log.d("httpParamTag", "url   - " + url);
        //遍历参数
        Map<String, String> map = https.getParam();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            Log.d("httpParamTag", entry.getKey() + ":" + entry.getValue());
        }

        try {
            Response response = https.post();
            if (response != null && response.isSuccessful()) {
                JSONObject json = new JSONObject(response.body().string());
                JSONObject dataJson = json.optJSONObject("data");
                if (dataJson != null) {
                    boolean isOK = dataJson.optBoolean("isOK", false);
                    if (isOK) {
                        postSuccess(callback, avatar);
                        return;
                    }
                }
            }
        } catch (Exception e) {
            postFailure(callback, e);
            return;
        }
        postFailure(callback, null);
    }

    private void realModifyGender(String num, String token, final String gender, final HttpCallback<String> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/modifySex";
        new Https().url(url)
                .addParam("mobilePhone", num)
                //.addParam("userId", "")
                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .addParam("sex", gender) // male  or  female
                .post(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Logger.i("", "");
                        if (callback != null) {
                            callback.onSuccess(gender);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    /**
     * 判断是不是分析师，逻辑：返回值是空，则不是分析师，不为空，则是分析师
     *
     * @param token
     * @return
     */
    private String isUserAnalyst(String token) {
        String userNo = GTConfig.instance().mCurName;
        if (TextUtils.isEmpty(userNo)) {
            return "";
        }
        List<AnalystData> list = new MyConcernRequest().getAllAnalystListSync(token);
        if (list != null && !list.isEmpty()) {
            for (AnalystData analyst : list) {
                if (analyst == null) {
                    continue;
                }
                if (userNo.equals(analyst.accountNo)) {
                    return analyst.userNo;
                }
            }
        }
        return "";
    }

    private <T> void postSuccess(final HttpCallback<T> callback, final T data) {
        if (callback != null) {
            AppMain.getApp().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    callback.onSuccess(data);
                }
            });
        }
    }

    private <T> void postFailure(final HttpCallback<T> callback, final Exception e) {
        if (callback != null) {
            AppMain.getApp().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    callback.onFailure(e);
                }
            });
        }
    }

    private void createUser(final String num, final HttpCallback<ProfileData> callback) {
        acquireChatToken(new ChatTokenRequest.OnTokenListener() {
            @Override
            public void onSuccess(String token) {
                String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/studio/checkMemberAndSave";
                new Https(url)
                        .addParam("userInfo[groupType]", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                        .addParam("userInfo[clientGroup]", "notActive")
                        .addParam("userInfo[mobilePhone]", num)
                        .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                        .addParam("token", token)
                        .post(new Https.ResponseCallback<String>() {
                            @Override
                            public void onSuccess(Request request, Response response, String result, int code) {
                                handleCreateUser(result, callback);
                            }

                            @Override
                            public void onFailure(Request request, IOException e) {
                                if (callback != null) {
                                    callback.onFailure(e);
                                }
                            }
                        });
            }

            @Override
            public void onFailure(Exception e) {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }

        });

    }

    private void handleCreateUser(String result, HttpCallback<ProfileData> callback) {
        if (callback == null) {
            return;
        }
        Exception exception = null;
        try {
            JSONObject json = new JSONObject(result);
            JSONObject dataJson = json.optJSONObject("data");
            if (dataJson != null) {
                JSONObject userJson = dataJson.optJSONObject("userInfo");
                ProfileData profile = parseUserInfo(userJson);
                callback.onSuccess(profile);
                return;
            }
        } catch (JSONException e) {
            exception = e;
        }
        callback.onFailure(exception);
    }

    public ProfileData fetchLocal() {
        return fetchLocal(GTConfig.instance().getLoginName());
    }

    public ProfileData fetchLocal(String username) {
        String fileName = username + "_profile.data";
        String str = CacheUtils.readFile(fileName);
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        return new Gson().fromJson(str, ProfileData.class);
    }

    void cache2Local(ProfileData data) {
        if (data == null) {
            return;
        }
        String fileName = GTConfig.instance().getLoginName() + "_profile.data";
        String str = new Gson().toJson(data);
        CacheUtils.writeFile(fileName, str);
    }

}
